<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use Laravel\Passport\Passport;
use Modules\Admin\Entities\Admin;
use Modules\Permission\Enums\RoleType;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        // 'App\Models\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        $this->registerPolicies();
        //passport 注册发出访问令牌并撤销访问令牌、客户端和个人访问令牌所必需的路由
        Passport::routes();
        //令牌有效期
        Passport::tokensExpireIn(now()->addMonths(1));
        //刷新令牌的令牌有效期
        Passport::refreshTokensExpireIn(now()->addDays(30));
        //个人令牌有效期
        Passport::personalAccessTokensExpireIn(now()->addMonths(6));

        if (!$this->app->routesAreCached()) {
            Passport::routes();
        }
        Gate::before(function ($user, $ability) {
            if ($user instanceof Admin) {
                return $user->hasRole('super admin') ?: null;
            }
            return null;
        });

        Gate::guessPolicyNamesUsing(function ($modelName) {
            $name = class_basename($modelName) . 'Policy';
            $arr = explode('\\', $modelName);
            if (count($arr) == 2) {
                $str = "$arr[0]\\Policies\\$name";
            } else {
                $str = "$arr[0]\\$arr[1]\\Policies\\$name";
            }
            return $str;
        });
        //
    }
}
